$import("biz.base.CompositePanel");


function getEditWin(){
	var win=Ext.getCmp('metaWin');
	 if(win)return win;
	 
	 var form = new Ext.FormPanel({
	        frame: true,
	        labelAlign: 'right',
	        labelWidth: 85,
	        width:200,
	        id:'meta_form',
	        closable:true,
	        waitMsgTarget: true,
	        defaults:{xtype:"textfield",width:190},
	 
	        items: [
	                {name: 'sid',xtype:'textfield',hidden:true},
	                {name: 'nid',xtype:'textfield',value:getMetaIdByCode("BT_META"),hidden:true},
	                {name: 'map.SID',fieldLabel:'编号',xtype:'textfield',readOnly:true,width:190},
	                {name: 'map.MID',xtype:'textfield',hidden:true},
	                {name: 'map.FLAG',xtype:'textfield',hidden:true,value:1},
	                {name: 'map.SEQ',xtype:'textfield',hidden:true,value:1},
	                {fieldLabel: '元数据类型',
	                	name: 'map.RANK',xtype:'combo',
	                	hiddenName:"map.RANK",
	                	valueField:'name',
						displayField:'text',
						mode:'local',
						allowBlank:false,
						triggerAction:'all',
						forceSelection:true,
	                	store:new Ext.data.JsonStore({
	                		fields:['name','text'],
	                		data:[
	                			{name:"WT_TABLE",text:"数据表"},
	                			{name:"WV_VIEWS",text:"SQL视图"},
	                			{name:"WQ_QUERY",text:"SQL查询"},
	                			{name:"WL_LINKS",text:"联表查询"},
	                			{name:"1011132",text:"枚举"},
	                			{name:"group",text:"分组"},
	                			{name:'DICT_LIST',text:"字段列表"}
	                		]
	                	}),
	                	width:190},
	                {	fieldLabel: '子项存储表',
	                	name: 'map.NAME',
	                	allowBlank:false,
	                	editable:false,
	                	width:190,
	                	xtype:'textfield'
	                },{
	                	fieldLabel: '编码',
	                	name:'map.CODE',
	                	width:190,
	                	allowBlank:false,
	                	xtype:'textfield',
	                },{fieldLabel: '别名',
	                	name:'map.TEXT',
	                	width:190,
	                	allowBlank:false,
	                	xtype:'textfield'
	                },{fieldLabel: '备注',
	                	name:'map.MARK',
	                	width:190,
	                	height:80,
	                	allowBlank:false,
	                	xtype:'textarea'
	                }],
	        buttons:[{
             text:'确认',
             handler:function(){
            	 var form=Ext.getCmp('meta_form').getForm();
            	 var sid=form.findField("map.SID").getValue()*1;
            	 var mid=form.findField("map.MID").getValue()*1;
             	var url=getContextBase()+"module/"+(sid<0?"Record-createJSON.action":"Record-updateJSON.action");
             	var conf={
 	  	   	  		    clientValidation: true,
 	  	   	  		    url: url,
 	  	   	  		    waitMsg:"保存中，请稍后...",
 	  	   	  		    success: function(form, action) {
 	  	   		  		  	var meta_tree=Ext.getCmp('meta_tree');
 	  	   		  		  	meta_tree.getNodeById(mid).reload();
 	  	   		  	var win=Ext.getCmp('metaWin');
 	             	win.hide();
 	  	   	     		},
 	  	   	  		    failure: function(form, action) {
 	  	   	  		 		return Ext.Msg.alert("结果","创建失败");
 	  	   	  		    	var win=Ext.getCmp('metaWin');
 	  	   	  		    	win.hide();
 	  	   	  		    }
 	  	   	  		};
 	  	    	form.submit(conf);
             }
         },{
             text: '取消',
             handler: function(){
             	var win=Ext.getCmp('metaWin');
             	win.hide();
             }
         }]
	 });
	 var win = new Ext.Window({
         layout:'fit',
         id:"metaWin",
         modal:true,
         title:'创建/编辑',
         width:500,
         height:280,
         plain: true,
         items: form,
         
     });
	 return win;
}
//初始化meta树展示控件
function initMetaTree(){
	var treeLoader = new Ext.tree.TreeLoader({
		dataUrl : '../module/Data-getMetaTree.action',
		nodeParameter:"id"
	});
	var metaTree = new Ext.tree.TreePanel({
		id : 'meta_tree',
		split : true,
		region : 'north',
		autoScroll : true,// 解决列表过长无法滚动的问题
		width : 250,
		height:300,
		enableDD:true,
		animate : true,
		floatable : false,// 仅点击箭头才能伸缩(无临时弹出):
		titleCollapse : true,
		rootVisible : false,
		lines : false,
		useArrows : true,
		loader : treeLoader,
		root : new Ext.tree.AsyncTreeNode({
			id : treeRootId,
			text : '根节点',
			attributes:{RANK:'group'}
		}),
		tbar:[{
			iconCls:'icon-folder',
			tooltip:{text:'新建分组'},
			handler:function(){
				var mid=null;
				var cur_node=metaTree["cur_node"];
				if(cur_node){
					var attrs=cur_node.attributes;
					if(attrs["RANK"]=="group"){
						mid=attrs["SID"];
					}else{
						mid=cur_node.parentNode.id;
					}
				}else{
					mid=metaTree.getRootNode().id;
				}
				
				var win=getEditWin();
				var form=Ext.getCmp('meta_form').getForm();
				form.findField('sid').setValue("-1");
				form.findField("map.SID").setValue("-1");
				form.findField("map.MID").setValue(mid);
				form.findField("map.SEQ").setValue(1);
				form.findField("map.NAME").setValue("bt_meta");
				form.findField("map.RANK").setValue("group");
				form.findField("map.CODE").setValue("");
				form.findField("map.TEXT").setValue("");
				win.show();
			}
		},{
			iconCls:'icon-detail',
			tooltip:{text:'新建元数据'},
			handler:function(){
				var mid=null;
				var cur_node=metaTree["cur_node"];
				if(cur_node){
					var attrs=cur_node.attributes;
					if(attrs["RANK"]=="group"){
						mid=attrs["SID"];
					}else{
						mid=cur_node.parentNode.id;
					}
				}else{
					mid=metaTree.getRootNode().id;
				}
				var win=getEditWin();
				var form=Ext.getCmp('meta_form').getForm();
				form.findField('sid').setValue("-1");
				form.findField("map.SID").setValue("-1");
				form.findField("map.MID").setValue(mid);
				form.findField("map.SEQ").setValue(1);
				form.findField("map.NAME").setValue("");
				form.findField("map.CODE").setValue("");
				form.findField("map.TEXT").setValue("");
				win.show();
			}
		},{
			iconCls:'icon-reset',
			text:'编辑',
			handler:function(){
				var mid=null;
				var cur_node=metaTree["cur_node"];
				if(!cur_node)return Ext.Msg.alert('提示','请先选择要编辑的节点');
				var attrs=cur_node.attributes;
				var pattrs=cur_node.parentNode.attributes;
				var win=getEditWin();
				var form=Ext.getCmp('meta_form').getForm();
				form.findField('sid').setValue(attrs.SID);
				form.findField("map.SID").setValue(attrs.SID);
				form.findField("map.MID").setValue(attrs.MID);
				form.findField("map.SEQ").setValue(attrs.SEQ);
				form.findField("map.RANK").setValue(attrs.RANK);
				form.findField("map.NAME").setValue(attrs.NAME);
				form.findField("map.CODE").setValue(attrs.CODE);
				form.findField("map.TEXT").setValue(attrs.text);
				form.findField("map.MARK").setValue(attrs.MARK);
				win.show();
			}
		},{
			text:'删除',
			iconCls:'icon-delete',
			handler:function(){
				Ext.Msg.confirm('提示',"确认删除此数据项(包含其字段信息)?",function(txt){
					if(txt=='no')return;
					var pNode=metaTree["cur_node"].parentNode;
					var url=getContextBase()+"module/Data-deleteDictMeta.action?sid="+metaTree["cur_node"].id;
					doHttpPost(url);
					pNode.reload();
				});
			}
		},{
			text:'刷新',
			iconCls:'icon-reload',
			handler:function(){
				metaTree.getRootNode().reload();
			}
		}]
	});
	metaTree.on('click',function(n){
		var attr=n.attributes;
		metaTree["cur_node"]=n;
		var dict_tab=Ext.getCmp('tab_panel'),id=attr.id;
		dict_tab.showSchema(attr.text+"-数据结构",id);
		var meta_attr_grid=Ext.getCmp('meta_attr_grid');
		meta_attr_grid.store.baseParams['filter.FID']=attr.id;
		meta_attr_grid.store.reload();
	});
	
	
	metaTree.on('movenode', function(tree,node,oldParent,newParent,index){
		var data=[];
		if(oldParent.id!=newParent.id){
			collectMod(oldParent, data);
			flag=true;
		}
		collectMod(newParent, data);
		var url=getContextBase()+"module/Data-updateMetaTree.action";
		Ext.Ajax.request( {
				url : url,
				method : 'post',
				params : {
					jsonStr:Ext.encode(data)
				},
				success: function() { 
					oldParent.reload();
					if(oldParent!=newParent)
						newParent.reload();
                },
                failure: function() {  
                	oldParent.reload();
					if(oldParent!=newParent)
						newParent.reload();
                }  
		    });
	});
	return metaTree;
};
function collectMod(node, o) {
	node.expand();
	node.eachChild(function(child) {
		var attr=child.attributes;
		var index=node.indexOf(child)+1;
		if(index!=attr["SEQ"]||attr["MID"]!=node.id){
			var a={sid:attr["id"],seq:index,mid:node.id};
			o.push(a);
		}
	});
}

function initMetaAttrGrid(){
	var companel = new CompositePanel('BT_ATTR');
	companel.formConfig=false;
	companel.dataConfig.baseParams['filter.FID']=0;
	companel.initBefore = function() {
		this.dataConfig.idProperty = "SID";
		this.dataConfig.sortInfo = {
			field : "SID",
			direction : "ASC"
		};
		this.gridConfig.xtype = 'editorgrid';
		this.gridConfig.id = 'meta_attr_grid';
		this.gridConfig.renderTo=null;
		this.gridConfig.region="center";
		this.gridConfig.clicksToEdit = 'auto';
		this.gridConfig.height = 400;
		this.gridConfig.viewConfig.forceFit=true;
		this.gridConfig.filter = true;
		this.gridConfig.width = 200;
		this.gridConfig.split = true;
		this.gridConfig.columnWidth=.25;
		this.getColsConfig=function(){
	            if( this.colsConfig ){
	           		return this.colsConfig;
	           	}
	           	var colsConfig={ names:[], items:[], model:[], filter:[], datum:[] };
	           	var fStore = storeHelper.get("modelFields", this.getMetaId());
	           	for ( var k = 0; k < fStore.getCount(); k++) {
	           		var rec = fStore.getAt(k);
	           		var colInfo = this.getColumnInfo( rec);
	           		var name=rec.get('NAME');
	           		if(this.attrConfig.idProperty==name){
	           			Ext.applyIf(colInfo,{editable:false,allowBlank:false});
	           		}
	           		if(name!="NAME"&&name!="CODE"&&name!="FLAG"&&name!="TEXT"){
	           			colInfo["hidden"]=true;
	           		}
	           		colsConfig.names.push(colInfo);
	           		colsConfig.items.push(colInfo);
	           		colsConfig.filter.push(this.getFiltersConfigByType( rec));
	           		colsConfig.model.push(this.getFiltersColumnsConfigByType( rec));
	           		colsConfig.datum.push(rec.data);
	           	}
	           	 this.colsConfig=colsConfig;
	           	 return this.colsConfig;
	           };
		};
	companel.gridConfig.tbar = companel.getButtons(['doAddNew','doDelete','doReload','doCommit']);
	companel.singleClick = function(grid, rowindex, e) {
		var row=grid.store.getAt(rowindex);
		if(!row)return;
	};
	companel.deleteSingle=function(rec){
		var rid = parseInt(rec.get(this.dataConfig.idProperty));
		if( rid>0 ){
		  var uri = "module/Data-getJsonDelete.action";
		  uri=uri+"?nid="+this.getMetaId()+"&sid="+rid;
		  var rs =Ext.decode(doHttpPost(getContextBase()+uri).text);
		  if(rs["success"]){
			  rec.store.remove(rec);
		  }else{
			  Ext.Msg.alert("删除失败","服务器通讯异常");
		  }
		}else{
			rec.store.remove(rec);
			return;		
		}
	};
	
	companel.doubleClick=function(){};
	companel.display();
	return companel.gridPanel;
}

function initTabPanel(region){
	var tabPanel=new Ext.TabPanel({
        id:'tab_panel',
        region:region,
        split:true,
        deferredRender:false,
        enableTabScroll:true,
        autoScroll: true,
        autoWidth:false,
        activeTab:0,
        bodyCssClass :'bgFilter',
        items:[]
	});
	tabPanel.layoutTabs=new HashMap();
	tabPanel.showData=function(title,name){
		this.showPageAsTab(title,name,"table_data");
	};
	tabPanel.showSchema=function(title,name){
		this.showPageAsTab(title,name,"meta_schema");
	};
	tabPanel.showPageAsTab = function(title,id,page){
		var layoutTabs=tabPanel.layoutTabs;
		if(!title)title=id;
		var tid = id || ++Ext.Component.AUTO_ID;
		var myTab=layoutTabs.get(tid);	
		if(!myTab ){
			var path='';
			if( path.substr(0,1)=="."|| path.substr(0,1)=="/"|| path.substr(0,4)=="http"){
				
			}else{
				path = '../meta/'+page+'.jsp?id='+id;
			}
			var tConf = {title:title, closable:true,autoScroll:true };
				tConf.html='<IFRAME src="'+path+'" frameborder="0" width="100%" height="100%" scrolling="auto" />';
			myTab = tabPanel.add(tConf);
			layoutTabs.put(tid,myTab);
			myTab.on("destroy",function(){layoutTabs.remove(tid);});
		}
		myTab.show();
		return myTab;
	};
	return tabPanel;
};


Ext.onReady(function() {
	Ext.QuickTips.init();
	var metaTree=initMetaTree();
	var metaAttrGrid=initMetaAttrGrid();
	
	var panel1=new Ext.Panel({
		layout:'border',
		region:'west',
		split:true,
		width:300,
		items:[metaTree,metaAttrGrid]
	});
	var tabPanel=initTabPanel('center');
	
	new Ext.Viewport({
		width : 1140,
		height : document.documentElement.clientHeight - 10,
		renderTo : 'container7',
        layout:'border',
        items : [panel1,tabPanel]
    });
});

